package com.sora.sora.server.service.impl;

import com.github.pagehelper.PageHelper;
//import com.sora.sora.common.mapper.TagMappers;
import com.sora.sora.common.model.bo.ImgBasicConvert;
import com.sora.sora.common.model.entity.ImgEntity;
import com.sora.sora.common.model.vo.ImgVO;
import com.sora.sora.server.mapper.ImgMapper;
import com.sora.sora.server.mapper.UserMapper;
import com.sora.sora.server.service.ImgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service("imgService")
public class ImgServiceImpl implements ImgService {

    @Resource
    ImgMapper imgMapper;

    @Resource
    UserMapper userMapper;

//    @Resource
//    TagMappers tagMapper;

    @Override
    public int count() {
        return imgMapper.getCount();
    }

    @Override
    public int count(int[] tags) {
        if (tags.length == 0) {
            return imgMapper.getCount();
        }
        int count = 0;
        for (int i = 0; i < tags.length; i++) {
            count += imgMapper.getCountByTag(tags[i]);
        }
        return count;
    }

    @Override
    public List<ImgVO> getAll(int page, int limit) {
        PageHelper.startPage(page, limit);
        List<ImgEntity> entities = imgMapper.queryAll();
        return ImgBasicConvert.INSTANCE.entitiesToVoes(entities);
    }

    @Override
    public List<ImgVO> queryByUploader(String name) {
        int uid = userMapper.queryIdByName(name);
        List<ImgEntity> imgEntities = imgMapper.queryByUploader(uid);
        return ImgBasicConvert.INSTANCE.entitiesToVoes(imgEntities);
    }

    @Override
    public List<ImgVO> queryByName(String name) {
        List<ImgEntity> imgEntities = imgMapper.queryByName(name);
        return ImgBasicConvert.INSTANCE.entitiesToVoes(imgEntities);
    }

    @Override
    public List<ImgVO> queryByTags(String[] tags) {
//        List<Integer> tagId = new ArrayList<>();
//        List<ImgEntity> entities = new LinkedList<>();
//        for (String tag : tags) {
//            tagId.addAll(tagMapper.queryIdByName(tag));
//        }
//        for (Integer tag : tagId) {
//            entities.addAll(imgMapper.queryByTag(tag));
//        }
//        return ImgBasicConvert.INSTANCE.entitiesToVoes(entities);
        return null;
    }

    @Override
    public List<Integer> deleteImgs(int uid, int[] imgIds) {

        List<Integer> result = new LinkedList<>();
        for (int imgId : imgIds) {
            if (imgMapper.queryUploaderById(imgId) != uid) {
                result.add(imgId);
                continue;
            }
            if (imgMapper.delImg(imgId) <= 0) {
                result.add(imgId);
            }
        }
        return result;
    }
}
